<template>
	<div class="admin-customer">
		<div class="customer-left">
			<div class="left-top" v-if="conversationList||false">{{totalCount}}</div>
			<div class="left-lcen" v-if="conversationList">
				<div class="lcen-li" :class="{'lcen-active':tabIndex==index}" v-for="(item,index) in conversationList.result" :key="index" @click="selectChat(index,item)">
					<x-contextmenu @chang="contextmenuTab" :index="index" :widget="item" :menuList="dialogueList">
						<div class="lcen-li_box">
							<div class="lcen-li-frame">
								<x-image class="lcen-li-img" :src="item.targetUser.avator" />
								<div class="lcen-li-mat" v-if="item.count!=0"></div>
							</div>
							<div class="lcen-li-text">
								<div class="lcen-li-text_p lcen-active-text">{{item.targetUser.nickName}}</div>
								<div class="lcen-li-text_p lcen-li-text_p2">{{item.content}}</div>
							</div>
						</div>
					</x-contextmenu>
				</div>
			</div>
			<div class="left-lbottom">
				<i class="el-icon-notebook-2"></i>
			</div>
		</div>
		<div class="customer-center">
			<div class="center-head" v-if="conversation">
				<x-image class="center-head-img" :src="conversation.targetUser.avator" />
				<div class="center-head-text">{{conversation.targetUser.nickName}}</div>
			</div>
			<div class="center-texeart" v-scroll="{auto: true}">
				<div class="center-texeart-li" v-for="(item, index) in messageList" :key="index">
					<x-contextmenu @chang="contextmenuTab" :index="index" :widget="item" :menuList="chatList">
						<x-chat @messageClick="messageClick" :message="item"></x-chat>
					</x-contextmenu>
				</div>
			</div>
			<div class="center-inptbox">
				<div class="inptbox-iconbox">
					<div class="inptbox-iconbox-left inptbox-iconbox-flexz">
						<el-upload :action="$ala.clientUploadApi()" :on-success="uploadSuccess" multiple :show-file-list="false" :headers="$ala.header('Api/StorageFile/upload')" accept=".jpg,.jpeg,.png,.gif">
							<img class="inptbox-iconbox-img" src="https://diyapi.5ug.com/wwwroot/uploads/api/256-116-382/2022-01-20/61e927a91f112d1408ccc1cc.png" />
						</el-upload>
						<el-upload :action="$ala.clientUploadApi()+'?fileType=2'" :on-success="videoSuccess" :show-file-list="false" multiple :headers="$ala.header('Api/StorageFile/upload')" accept=".mp4,.MP4">
							<img class="inptbox-iconbox-img" src="https://diyapi.5ug.com/wwwroot/uploads/api/256-116-382/2022-01-20/61e927a91f112d1408ccc1ce.png" />
						</el-upload>
						<el-upload :action="$ala.clientUploadApi()+'?fileType=2'" :on-success="audioSuccess" :show-file-list="false" multiple :headers="$ala.header('Api/StorageFile/upload')" accept=".mp3,.amr,.m4a">
							<img class="inptbox-iconbox-img" src="https://diyapi.5ug.com/wwwroot/uploads/api/256-116-382/2022-01-20/61e928901f112d1408ccc1e0.png" />
						</el-upload>
					</div>
					<div class="inptbox-iconbox-left" v-if="false">
						<i class="el-icon-sunny inptbox-iconbox-icon"></i>
						<i class="el-icon-food inptbox-iconbox-icon"></i>
						<i class="el-icon-orange inptbox-iconbox-icon"></i>
					</div>
				</div>
				<div class="inptbox-send">
					<textarea class="inptbox-send-divcont" v-model="messageContent" @paste="pasteChang"></textarea>
				</div>
				<div class="inptbox-buts">
					<div class="inptbox-bt" @click="textMessage">发送</div>
				</div>
			</div>
		</div>
		<div class="customer-right">
			<ul class="right-ul">
				<li class="right-li" v-for="(divItem,divIndex) in quickReplyList" :key="divIndex">
					<div class="right-li-txt" @click="checkTab(divIndex)">
						<i class="el-icon-arrow-right" :class="{'right-li-icon':divItem.check==true}"></i>
						{{divItem.name}}
					</div>
					<ul class="right-li-cul" :class="{'right-li-active':divItem.check==true}">
						<li class="right-li-cli" v-for="(cItem,cIndex) in divItem.items" :key="cIndex" @dblclick="selectQuickReply(cItem)">{{cItem.name}}</li>
					</ul>
				</li>
			</ul>
			<div class="right-footer">
				<router-link :to="'/Admin-'+$ala.themeType()+'/QuickReply/List'">管理快捷话术</router-link>
			</div>
		</div>
	</div>
</template>
<script>
	import ala from '@/service/ala'
	import mixin from '@/service/mixins'
	export default {
		mixins: [mixin],
		directives: {
			scroll: {
				bind(el, binding, vnode) {
					const pause = (e) => {
						let auto = binding.value ? binding.value.auto : false
						let scrolled = el.scrollTop + el.clientHeight + 1 < el.scrollHeight
						let timeout
						window.clearTimeout(timeout)
						timeout = setTimeout(() => {
							if (auto && scrolled) {
								el.setAttribute('v-scroll2-manually', 'yes')
							} else if (auto && !scrolled) {
								el.setAttribute('v-scroll2-manually', '')
							} else {
								el.removeEventListener('scroll', pause)
							}
						}, 600)
					}
					el.addEventListener('scroll', pause)
				},
				update(el, binding, vnode) {
					if (!el.getAttribute('v-scroll2-manually')) {
						vnode.context.$nextTick(() => {
							el.scrollTop = el.scrollHeight - el.clientHeight
						})
					}
				}
			}
		},
		data() {
			return {
				conversationList: null, // 会话列表
				conversation: null, // 当前会话
				messageList: [], // 消息列表
				msgTimeDict: [],
				pageInfo: {
					pageIndex: 1,
					pageCount: 1
				}, // 页面信息
				searchInput: {
					keyword: null,
					pageIndex: 1
				},
				totalCount: 0, // 未读消息数量
				quickReplyList: null, // 快捷回复
				contentType: 1, // 内容类型
				messageContent: '',
				tabIndex: 0,
				dialogueList: [{
					name: '删除记录',
					type: 'imConversationDelete'
				}],
				chatList: [{
						name: '删除',
						type: 'imMessageDelete'
					},
					{
						name: '复制',
						type: 'dialogueEmpty'
					}
				]
			}
		},
		created() {
			window.addEventListener('keydown', this.handleKeyDown, true)
		},
		mounted() {
			this.init()
			this.listen()
		},
		methods: {
			async init() {
				this.conversationList = await this.$api.imConversationList(this.searchInput)
				this.updateTotalCount(this.conversationList.totalCount)
				this.quickReplyList = await this.$api.imQuickreplayList()
				if (this.conversationList) {
					this.selectChat(this.tabIndex, this.conversationList.result[this.tabIndex])
				}
			},
			// 更新未读消息数量
			updateTotalCount(count) {
				this.totalCount = count
				this.$bus.$emit('global_totalUnReadCount', count)
			},
			// 监听回复消息
			async listen() {
				this.$bus.$on('ImChatReceiveMessage', async (data) => {
					var message = {
						avator: this.conversation.targetUser.avator,
						userId: this.conversation.targetUser.id,
						isSelf: false,
						...data
					}
					if (!this.msgTimeDict.includes(message.time)) {
						this.msgTimeDict.push(message.time)
						this.messageList.push(message) // 接手对方发送的消息
						this.messageList.sort((lhs, rhs) => {
							return lhs.time - rhs.time
						})

						await this.$api.msgReceiveFeedback(this.conversation.sendUser.id, data.id)
					} else {
						await this.$api.msgReceiveFeedback(this.conversation.sendUser.id, data.id)
					}
				})
				this.$bus.$on('ImChatUnReadCount', async (data) => {
					// 监听未读消息数量
					this.updateTotalCount(data)
				})
			},
			handleKeyDown(e) {
				if (e.keyCode === 13) {
					this.send()
					e.preventDefault()
				}
			},
			// 消息点击
			messageClick(message) {

			},
			async selectChat(tindex, item) { //右侧聊天消息
				this.tabIndex = tindex //左侧选中index
				this.conversation = await this.$api.imConversation(item)
				var response = await this.$api.imMessageHistory(this.conversation, 1)
				this.messageList = response.messageList
				this.pageInfo = response.pageInfo
				if (item.count > 0) {
					this.updateTotalCount(this.totalCount - item.count)
				}
			},
			// 发送消息
			async send() {
				if (this.messageContent) {
					var message = {
						avator: this.conversation.sendUser.avator,
						userId: this.conversation.sendUser.id,
						isSelf: true,
						content: this.messageContent,
						type: this.contentType
					}
					this.messageList.push(message) // 自己的聊天窗口增加消息
					await this.$api.imSend(message, this.conversation.id)
					this.messageContent = ''
				}
			},
			textMessage() { //文字消息
				this.contentType = 1
				this.send()
			},
			checkTab(cIndex) {
				this.quickReplyList[cIndex].check = !this.quickReplyList[cIndex].check
			},
			selectQuickReply(val) {
				this.messageContent = val.name
			},
			async contextmenuTab(vData, tItem) { //删除、复制会话聊天信息操作
				await this.$api[tItem.type](vData.id)
				this.init()
			},
			uploadSuccess(res, file) { //点击图片上传
				if (res.status === 1) {
					this.contentType = 4
					this.messageContent = res.result.path
					this.send()
					this.init()
				}
			},
			videoSuccess(res, file) { //点击视频上传
				if (res.status === 1) {
					this.contentType = 9
					this.messageContent = res.result.path
					this.send()
					this.init()
				}
			},
			async audioSuccess(res, file) { //点击音频上传
				if (res.status === 1) {
					this.contentType = 2
					this.messageContent = {}
					this.messageContent.duration = await this.getTimes(this.$ala.urlImage(res.result.path))
					this.messageContent.content = res.result.path
					this.send()
					this.init()
				}
			},
			getTimes(url) { //获取音频时长
				return new Promise((resolve) => {
					var audioElement = new Audio(url)
					audioElement.addEventListener('loadedmetadata', (_event) => {
						resolve(parseInt(audioElement.duration))
					})
				})
			},
			async pasteChang(e) { //图片粘贴功能
				var imageLists = []
				if (e.clipboardData) {
					for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
						var item = e.clipboardData.items[i]
						if (item && item.kind === 'file') {
							var file = item.getAsFile()
							var formData = new FormData()
							formData.append('file', file)
							imageLists.push(formData)
						}
					}
				} else if (window.clipboardData) {
					alert('ie9及其上')
				} else {
					alert('浏览器版本过低')
				}
				var this_ = this
				imageLists.forEach(async (res) => {
					var repoes = await this.$ala.httpPost('Api/StorageFile/upload', res)
					if (repoes) {
						this_.contentType = 4
						this_.messageContent = repoes.path
						this_.send()
					}
				})
			}
		}
	}
</script>
<style lang="scss">
	@import "./index.scss";
</style>